package com.itheima.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.*;
import com.itheima.service.MemberService;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 后管会员管理
 * ①增删改查
 * ②会员批量导出excel
 */
@RestController
@RequestMapping("/member")
public class MemberController {
    @Reference
    private MemberService memberService;

    //饼图
    @RequestMapping("/getMemberReport")
    public Map getMemberReport() throws Exception {
        Map memberReport = memberService.getMemberReport();
        return memberReport;
    }

    //柱形图





    //进入后管会员页面的分页查询
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) throws Exception {
        return memberService.findPage(queryPageBean);
    }

    //选项里的咨询师数据回显
    @RequestMapping("/findUser")
    public List<User> findUser() {
        List<User> user = memberService.findUser();
        return user;
    }

    //新增按钮功能
    @RequestMapping("/add")
    public Result add(@RequestBody Member member) {
        try {
            memberService.add(member);
            return new Result(true, MessageConstant.ADD_MEMBER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_MEMBER_FAIL);
        }
    }
    //删除按钮
    @RequestMapping("/delete")
    public Result delete(Integer id) {
        try {
            memberService.delete(id);
            return new Result(true, MessageConstant.DELETE_MEMBER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.DELETE_MEMBER_FAIL);
        }
    }
    //编辑数据回显
    @RequestMapping("/findById")
    public Member findById(Integer id) {
        return memberService.findById(id);
    }
    //编辑提交按钮
    @RequestMapping("/edit")
    public Result edit(@RequestBody Map map){
        try {
            memberService.edit(map);
            return  new Result(true,MessageConstant.EDIT_MEMBER_SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return  new Result(false,MessageConstant.DELETE_MEMBER_SUCCESS);
        }
    }




    //批量导出会员预约数据
    @RequestMapping("/exportMemberOrderReport")
    public Result exportMemberOrderReport(@RequestParam("multiple") String[] multiple, HttpServletRequest request, HttpServletResponse response) {
        try {
            List<Map<String, Object>> memberInfo = new ArrayList<>();
            for (String s : multiple) {
                int id = Integer.parseInt(s);
                //根据会id查询是否预约了套餐，如果没有，就不导入excel
                int count = memberService.findCountByMemberId(id);

                if (count == 0) {
                    continue;//跳出当次循环
                }
                System.out.println("获取到的id是：" + id);
                List<Map<String, Object>> members = memberService.findmemberInfo(id);


                System.out.println(members);


                for (Map<String, Object> member : members) {
                    memberInfo.add(member);
                }
            }

            //获取excel模板文件绝对路径
            String filePath = request.getSession().getServletContext().getRealPath("template") + File.separator + "MemberOrderInfo.xlsx";

            //读取模板文件创建Excel表格对象
            XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File(filePath)));
            //创建工作簿样式对象
            XSSFCellStyle style = workbook.createCellStyle();
            //设置日期样式
            style.setDataFormat(workbook.createDataFormat().getFormat("yyyy-MM-dd"));
            //获取第一个表格
            XSSFSheet sheet = workbook.getSheetAt(0);
            XSSFRow row = sheet.getRow(0);//获取行对象

            //定义初始行号
            int rowNumber = 1;
            for (Map map : memberInfo) {
                if (map.size() == 0) {
                    continue;
                }
                String name = (String) map.get("mname");
                String sex = (String) map.get("sex");
                if ("1".equals(sex)) {
                    sex = "男";
                } else {
                    sex = "女";
                }
                String phoneNumber = (String) map.get("phoneNumber");
                Date orderDate = (Date) map.get("orderDate");
                String setmeal = (String) map.get("setmeal");

                List<String> checkGroups = (List) map.get("checkGroup");
                List<String> checkItems = (List) map.get("checkItem");
                row = sheet.getRow(rowNumber++);
                if (row == null) {
                    row = sheet.createRow(--rowNumber);
                }
                row.createCell(0).setCellValue(name);
                row.createCell(1).setCellValue(sex);
                row.createCell(2).setCellValue(phoneNumber);
                row.createCell(3).setCellValue(orderDate);
                row.getCell(3).setCellStyle(style);//设置日期样式
                row.createCell(4).setCellValue(setmeal);
                row.createCell(5).setCellValue(checkGroups.toString());
                row.createCell(6).setCellValue(checkItems.toString());
            }

            //通过输出流进行文件下载
            ServletOutputStream sos = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-Disposition", "attachment;filename=memberOrderInfo.xlsx");
            workbook.write(sos);
            sos.flush();
            sos.close();
            workbook.close();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "下载失败");
        }
    }
//    /**
//     * 分页查询
//     */
//
//    @RequestMapping("/findPage")
//    public Result findPage(@RequestBody QueryPageBean queryPageBean) {
//        try {
//            PageResult pageResult = memberService.pageQuery(queryPageBean);
//            return new Result(true, MessageConstant.ADD_MEMBER_SUCCESS,pageResult);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return new Result(false, MessageConstant.ADD_MEMBER_FAIL);
//        }
//    }
//
//    /**
//     * 新增会员
//     */
//    @RequestMapping("/add")
//    public Result addMember(@RequestBody Member member) {
//        try {
//            memberService.addMember(member);
//            return new Result(true, MessageConstant.ADD_MEMBER_SUCCESS);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return new Result(false, MessageConstant.ADD_MEMBER_FAIL);
//        }
//    }
//
//    /**
//     * 编辑回显数据(根据会员id回显数据)
//     */
//    @RequestMapping("/findById")
//    public Result findById(Integer id) {
//        try {
//            Member member = memberService.findById(id);
//            return new Result(true, MessageConstant.QUERY_MEMBERDATA_SUCCESS, member);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return new Result(false, MessageConstant.QUERY_MEMBERDATA_FAIL);
//        }
//    }
//
//    /**
//     * 编辑更新会员数据
//     */
//    @RequestMapping("/edit")
//    public Result edit(@RequestBody Member member) {
//        try {
//            memberService.edit(member);
//            return new Result(true, MessageConstant.EDIT_MEMBER_SUCCESS);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return new Result(false, MessageConstant.EDIT_MEMBER_FAIL);
//        }
//    }
//
//    /**
//     * 删除会员
//     */
//    @RequestMapping("/delete")
//    public Result delete(Integer id) {
//        try {
//            memberService.delete(id);
//            return new Result(true, MessageConstant.DELETE_MEMBER_SUCCESS);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return new Result(false, MessageConstant.DELETE_MEMBER_FAIL);
//        }
//    }
//
//    /**
//     * 批量导出excel文件
//     */
//    @RequestMapping("/exportMember")
//    public Result exportMember(Integer[] ids, HttpServletRequest request, HttpServletResponse response) {
//        //获得Excel模板文件绝对路径
//        try {
//            String temlateRealPath = request.getSession().getServletContext().getRealPath("template") + File.separator + "MemberOrderInfo.xlsx";
//
//            //读取模板文件创建Excel表格对象
//            XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File(temlateRealPath)));
//
//            XSSFSheet sheet = workbook.getSheetAt(0);
//            int rowNum = 1;
//            for (Integer id : ids) {
//                List<Order> orders = memberService.findOrderIdByMember(id);
//                Member member = memberService.findById(id);
//                XSSFRow row = sheet.createRow(rowNum);
//                row.createCell(0).setCellValue(member.getName());
//                row.createCell(1).setCellValue(member.getSex());
//                row.createCell(2).setCellValue(member.getPhoneNumber());
//                if (orders != null && orders.size() > 0) {
//                    for (Order order : orders) {
//                        row.createCell(3).setCellValue(order.getAddressName());
//
//                        System.out.println("MemberController");
//                        System.out.println(order.getSetmealId() + "-----------");
//
//                        Setmeal setmealDetail = memberService.findSetmealDetail(order.getSetmealId());
//                        if (setmealDetail != null) {
//                            row.createCell(4).setCellValue(setmealDetail.getName());
//                            List<CheckGroup> list = setmealDetail.getCheckGroups();
//                            List<String> checkGroupsName = new ArrayList<>();
//                            List<String> checkItemsName = new ArrayList<>();
//                            for (CheckGroup checkGroup : list) {
//                                checkGroupsName.add(checkGroup.getName());
//                                List<CheckItem> checkItems = checkGroup.getCheckItems();
//                                for (CheckItem checkItem : checkItems) {
//                                    checkItemsName.add(checkItem.getName());
//                                }
//                            }
//
//                            row.createCell(5).setCellValue(checkGroupsName.toString());
//
//                            row.createCell(6).setCellValue(checkItemsName.toString());
//                        }
//                    }
//                }
//                rowNum++;
//            }
//            ServletOutputStream out = response.getOutputStream();
//            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");
//            workbook.write(out);
//
//            out.flush();
//            out.close();
//            workbook.close();
//            return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS, null);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL, null);
//        }
//    }
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//


    @RequestMapping("/findByAge")
    public Result findByAge(){
        return memberService.findByAge();
    }
}
